package com.bagua.sbbcshop.tool;

import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

/**
 * Json 工具类
 * @author xhou
 */
public class JsonUtil {

    private final static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(Feature.ALLOW_COMMENTS, true);
        objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    }

    //获取一个Jackson对象进行处理,是一个单例，使用不频繁的地方才调用，如果有并发要求的请单独定义
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    //list转为String
    public static String listToString(List list) throws JsonProcessingException {
        if (list == null || list.size() < 1) {
            return "";
        }
        String json = objectMapper.writeValueAsString(list);
        return json;
    }
    //Map转为String
    public static String mapToString(Map map) throws JsonProcessingException {
        if (map == null || map.size() < 1) {
            return "";
        }
        String json = objectMapper.writeValueAsString(map);
        return json;
    }
}
